package com.cefa.edu.service;

import com.cefa.edu.dao.EducationLevelMapper;
import com.cefa.edu.dao.StudentStageDataMapper;
import com.cefa.edu.dao.UserRoleMapper;
import com.cefa.edu.model.ClassInfo;
import com.cefa.edu.model.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class AuthService {

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    EducationLevelMapper educationLevelMapper;

    @Autowired
    StudentStageDataMapper studentStageDataMapper;

    public List<ClassInfo> getAuthClass(Integer userid) {
        List<ClassInfo> authClass = null;
        int level = findRoleLevel(userid);

        if (userid == 1 || userid == 2) {
            authClass = adminAuthClass(userid, level);
        } else if (userid == 3 || userid == 4) {
            authClass = teacherAuthClass(userid, level);
        }
        return authClass;
    }

    private List<ClassInfo> adminAuthClass(Integer userid, Integer level) {
        List<ClassInfo> classInfos = new ArrayList<>();
        if (level == 1) {
            classInfos = educationLevelMapper.findByLevel12("p_id", level);
        } else if (level == 2) {
            classInfos = educationLevelMapper.findByLevel12("g_id", level);
        }
        return classInfos;
    }

    private List<ClassInfo> teacherAuthClass(Integer userid, Integer level) {
        return educationLevelMapper.findByLevel34(userid);
    }

    private int findRoleLevel(Integer userid) {
        List<Integer> roleIds = userRoleMapper.getRoleIds(userid);
        Collections.sort(roleIds);
        return roleIds.get(0);
    }


    public List<StudentInfo> findStudentInfo(Integer userid) {
        List<StudentInfo> students=null;
        int roleLevel = findRoleLevel(userid);
        if (roleLevel >= 1 && roleLevel <= 4) {
            List<ClassInfo> authClass = getAuthClass(userid);
            StringBuilder levels = new StringBuilder();
            for (ClassInfo classInfo : authClass) {
                levels.append(classInfo.getId()).append(",");
            }
            if (levels.length() > 0) {
                levels.substring(0, levels.length() - 1);
            }
            students = studentStageDataMapper.findStudentByLevelId(levels.toString());
        }
        return students;
    }
}
